﻿using System;
using System.Collections.Generic;
using System.Linq;
using DNT.RavenQA.Core.Extensions;
using DNT.RavenQA.Core.Models;
using DNT.RavenQA.Web.Infrastructure.QueryModel;
using Raven.Client;

namespace DNT.RavenQA.Web.ViewModels
{
    public class UserDetailsViewModel
    {
        public static UserDetailsViewModel Build(IDocumentSession session,
                                                 Int32 userId,
                                                 User currentUser,
                                                 IQuery<Question> query)
        {
            session.EnsureIsNotNull("session");
            query.EnsureIsNotNull("query");

            var user = session.Load<User>(userId);

            if (user.IsNull())
                throw new NonExistingUserException();

            var questions = query.Execute(session)
                                 .Take(10)
                                 .ToList();

            return new UserDetailsViewModel
                       {
                           UserName = user.Name,
                           GravatarUrl = user.GetGravatarUrl(128),
                           NumberOfContributes = user.ContributionsCount,
                           Questions = questions.Select(QuestionSummary.Build),
                           IsCurrentUser = user == currentUser
                       };
        }

        public IEnumerable<QuestionSummary> Questions { get; private set; }

        public Int32 NumberOfContributes { get; private set; }

        public String GravatarUrl { get; private set; }

        public String UserName { get; private set; }

        public Boolean IsCurrentUser { get; private set; }

        public class QuestionSummary
        {
            public static QuestionSummary Build(Question question)
            {
                question.EnsureIsNotNull("question");

                return new QuestionSummary
                {
                    QuestionId = question.Key,
                    Title = question.Title,
                    AnswersCount = question.AnswersCount
                };
            }

            public Int32 AnswersCount { get; private set; }

            public String Title { get; private set; }

            public Int32 QuestionId { get; private set; }
        }
    }
}